package com.itheima.stock.controller;

import com.itheima.stock.pojo.entity.SysUser;
import com.itheima.stock.service.UserService;
import com.itheima.stock.vo.req.LoginReqVo;
import com.itheima.stock.vo.resp.CaptchaVo;
import com.itheima.stock.vo.resp.LoginRespVo;
import com.itheima.stock.vo.resp.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@Api(value = "/api", tags = "用户信息处理")
@RestController
@RequestMapping("/api")
public class UserController {

    @Autowired
    private UserService userService;

    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", dataType = "string", name = "userName", value = "", required = true)
    })
    @ApiOperation(value = "根据用户名获取用户信息", httpMethod = "GET")
    @GetMapping("/user/{userName}")
    public SysUser getUserByUserName(@PathVariable String userName){
        return userService.getUserByUserName(userName);
    }

    /**
     * 用户登录功能
     * @param vo
     * @return
     */
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "body", dataType = "LoginReqVo", name = "vo", value = "", required = true)
//    })
//    @ApiOperation(value = "用户登录功能", notes = "用户登录功能", httpMethod = "POST")
//    @PostMapping("/login")
//    public R<LoginRespVo> userLogin(@RequestBody @Valid LoginReqVo vo, Errors errors){
//        if (errors.hasErrors()) {
//            List<FieldError> fieldErrors = errors.getFieldErrors();
//            for (FieldError fieldError : fieldErrors) {
//                String field = fieldError.getField();
//                String errorMsg = fieldError.getDefaultMessage();
//                return R.error(field+errorMsg);
//            }
//        }
//        return userService.login(vo);
//    }

    @PostMapping("/login")
    public R<LoginRespVo> userLogin(@RequestBody @Valid LoginReqVo vo){
        R<LoginRespVo> r= this.userService.login(vo);
        return r;

    }

    /**
     * 生成图片验证码功能
     * @return
     */
    @ApiOperation(value = "生成图片验证码功能", notes = "生成图片验证码功能", httpMethod = "GET")
    @GetMapping("/captcha")
    public R<CaptchaVo> getCaptchaImage(){
        return userService.getCaptchaImage();
    }

}
